package com.springboot.frame.starter;

import com.springboot.frame.starter.applet.WxAppletTools;
import com.springboot.frame.starter.pay.v2.WxV2Pay;
import com.springboot.frame.starter.pay.v3.WxV3Pay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author liheng
 * @ClassName WxSdkAutoConfiguration
 * @Description
 * @date 2021-07-28 13:54
 */
@Configuration
@ConditionalOnProperty(name = "wx.conf.enabled")
@EnableConfigurationProperties(WeixinProperties.class)
public class WxSdkAutoConfiguration {
    private final WeixinProperties weixinProperties;

    @Autowired
    public WxSdkAutoConfiguration(WeixinProperties weixinProperties) {
        this.weixinProperties = weixinProperties;
    }


    /**
     * 当不存在此 wxRestTemplate 使用此方法的bean注入
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "wxRestTemplate")
    public RestTemplate wxRestTemplate() {
        //复杂构造函数的使用
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 设置超时
        requestFactory.setConnectTimeout(6000);
        requestFactory.setReadTimeout(6000);
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }

    /**
     * 当不存在此 wxCacheTemplate 使用此方法的bean注入
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "wxCacheTemplate")
    public WxCacheTemplate wxCacheTemplate() {
        WxCacheTemplate<String> wxCacheTemplate = new WxCaffineCache();
        return wxCacheTemplate;
    }

    @Bean
    @ConditionalOnMissingBean(name = "wxAppletTools")
    public WxAppletTools wxAppletTools() {
        return new WxAppletTools(wxRestTemplate(), weixinProperties, wxCacheTemplate());
    }

    @Bean
    @ConditionalOnMissingBean(name = "wxV2Pay")
    public WxV2Pay wxV2Pay() {
        return new WxV2Pay(weixinProperties);
    }


    @Bean
    @ConditionalOnMissingBean(name = "wxV3Pay")
    public WxV3Pay wxV3Pay() {
        return new WxV3Pay(weixinProperties);
    }
}
